<?php

namespace common\service;

use Yii;
use common\models\YwAccount;
use common\models\YwAccountLog;
use common\models\YwCash;
use common\models\YwCashRedpack;
use common\models\YwRecharge;
use common\models\YwReview;

class YsRedpack extends Service{
    
    public $remarkList = [
        1 => ['act_name'=>'阅读是一种信仰','wishing'=>'新年新气象','remark'=>'感恩互动'],
    ];
    
    public function getRedpackForUpdate($id){
        $sql = 'SELECT * FROM '.YwCashRedpack::tableName().' WHERE id = :id FOR UPDATE';
        $params = [':id' => $id];
        return YwCashRedpack::findBySql($sql, $params)->one();
    }
    
    public function sendRedpack($redpack){
        $transaction = Yii::$app->db->beginTransaction();
        try {
            $ywCashRedpack = $this->getRedpackForUpdate($redpack->id);
            if(empty($ywCashRedpack) || $ywCashRedpack->status != 0){
    			Yii::error('YsRedpack/sendRedpack get YwCashRedpack status 异常 attributes:'.empty($ywCashRedpack)?'NULL':print_r($ywCashRedpack->attributes,true));
    			$transaction->rollBack();
    			return false;
    		}
            $ywCashRedpack->status = 1;
            if($ywCashRedpack->save(false,['status','updated_at']) === false){
                Yii::error('YsRedpack/sendRedpack YwCashRedpack set status:1 save errors:'.print_r($ywCashRedpack->errors,true), true);
                $transaction->rollBack();
                return false;
            }
            $transaction->commit();
        } catch (Exception $ex) {
            Yii::error('YsRedpack/sendRedpack Exception attributes:'.print_r($redpack->attributes,true).' Exception:'.print_r($ex,true));
    		$transaction->rollBack();
            return false;
        }
        
        $redpackRemark = $this->remarkList[$ywCashRedpack->type];
        $sendRedpack = YsWeixin::service()->sendRedpack($ywCashRedpack->site_id,$ywCashRedpack->mch_billno,$ywCashRedpack->re_openid,$ywCashRedpack->total_amount,$redpackRemark['act_name'],$redpackRemark['wishing'],$redpackRemark['remark']);
        $ywCashRedpack->send_param = $sendRedpack['send_xml'];
        $ywCashRedpack->send_result = $sendRedpack['result_xml'];
        $ywCashRedpack->send_at = time();
        if(!empty($sendRedpack['result_obj'])){
            $ywCashRedpack->send_code = trim($sendRedpack['result_obj']->result_code);
        }
        if($ywCashRedpack->save(false,['send_param','send_result','send_code','send_at','updated_at']) === false){
            Yii::error('YsRedpack/sendRedpack YwCashRedpack set send_data save errors:'.print_r($ywCashRedpack->errors,true), true);
            $transaction->rollBack();
            return false;
        }
        return $ywCashRedpack->send_code;
    }
    
    public function queryRedpack($redpack){
        $queryRedpack = YsWeixin::service()->queryRedpack($redpack->site_id,$redpack->mch_billno);
        $redpack->query_param = $queryRedpack['send_xml'];
        $redpack->query_result = $queryRedpack['result_xml'];
        $redpack->query_at = time();
        if(!empty($queryRedpack['result_obj'])){
            $resultObj = $queryRedpack['result_obj'];
            $redpack->query_code = trim($resultObj->result_code);
            
            $err_code = isset($resultObj->err_code)?trim($resultObj->err_code):'';
            if((empty($redpack->send_code) || $redpack->send_code == 'FAIL') && $redpack->query_code == 'FAIL' && $err_code == 'NOT_FOUND'){
                $redpack->status = 3;
            }elseif(trim($resultObj->return_code) == 'SUCCESS' && trim($resultObj->result_code) == 'SUCCESS' ){
                switch(trim($resultObj->status)){
                    case 'SENT': $redpack->status = 2; break;//已发放待领取
                    case 'FAILED': $redpack->status = 3; break;//发放失败
                    case 'RECEIVED': $redpack->status = 5; break;//已领取
                    case 'REFUND': $redpack->status = 4; break;//已退款
                }
            }
        }
        if($redpack->save(false,['query_param','query_result','query_code','query_at','status','updated_at']) === false){
            Yii::error('YsRedpack/queryRedpack YwCashRedpack set query_data save errors:'.print_r($redpack->errors,true), true);
            return false;
        }

        if($redpack->status == 5 && $redpack->cashInfo->status == 3){
            YsAccount::service()->cashSuccess($redpack->cashInfo->id);
        }

        return $redpack->query_code.' '.$redpack->statusList[$redpack->status];
    }
    
    /**
     * 发送晒单红包
     * @param type $id
     */
    public function sendReviewRedpack($id){
        $reviewInfo = YwReview::findOne($id);
        if(empty($reviewInfo) || $reviewInfo->status != 1){
            return false;
        }
        
        $reviewInfo->status = 5;
        if($reviewInfo->save() == false){
            Yii::error('YsRedpack/sendReviewRedpack YwReview Update status 5 return false:Data'.print_r($reviewInfo->attributes,true).' Errors:'.print_r($reviewInfo->errors,true));
            return false;
        }
        
        $ywRecharge = new YwRecharge;
        $ywRecharge->setAttributes([
            'user_id'=>$reviewInfo->user_id,
            'type'=>'redpack',
            'related_id'=>$reviewInfo->id,
            'money'=>$reviewInfo->money,
            'remark'=>'',
            'ip'=>$reviewInfo->ip,
            'status'=>0
        ]);
        if($ywRecharge->save() == false){
            Yii::error('YsRedpack/sendReviewRedpack save YwRecharge return false:Data'.print_r($ywRecharge->attributes,true).' Errors:'.print_r($ywRecharge->errors,true));
            return false;
        }

        $ywCash = new YwCash;
        $ywCash->setAttributes([
            'user_id'=>$reviewInfo->user_id,
            'type'=>2,//晒单红包
            'pay_way'=>2,
            'total'=>$reviewInfo->money,
            'fee'=>0,
            'money'=>$reviewInfo->money,
            'status'=>1,
            'ip'=>$reviewInfo->ip,
            'remark'=>'美文服务晒单',
        ]);
        if($ywCash->saveCash() == false){
            Yii::error('YsRedpack/sendReviewRedpack save YwCash return false:Data'.print_r($ywCash->attributes,true).' Errors:'.print_r($ywCash->errors,true));
            return false;
        }
        
        $appid = YsWeixin::service()->appid;
//        $userWeixinInfo = \common\models\YwUserWeixin::findOne(['user_id'=>$reviewInfo->user_id,'appid'=>$appid]);
        $userWeixinInfo = YsUser::service()->canCash($reviewInfo->user_id);
        if(YsAccount::service()->cashRedpack($ywCash->id,$userWeixinInfo->openid) === false){
            Yii::error('YsRedpack/sendReviewRedpack cashRedpack return false');
            return false;
        }
        return true;
    }
}
